import QtQuick 1.1
import com.nokia.meego 1.0
import com.nokia.extras 1.0
import "calcJSLib.js" as CalcJSLib

Page {
    id: timeDiffPage
    tools: commonTools

    Rectangle {
        id: container
        color: "#4c0094"

        anchors.left: parent.left
        anchors.leftMargin: 0
        anchors.top: parent.top
        width: timeDiffPage.width
        height: timeDiffPage.height

        gradient: Gradient {
            GradientStop {
                position: 0.00;
                color: "#c7b8fa";
            }
            GradientStop {
                position: 0.60;
                color: "#ffffff";
            }
        }

        SipAttributes {
            id:customSipAttributes
            actionKeyEnabled: true
            actionKeyHighlighted: true
            actionKeyLabel: qsTr("Calculate")
        }

        Row {
            id: rowAppLogoName

            Image {
                id: appLogo
                x: 0; y: 0
                width: 64; height: 64
                source: "qrc:/icon_withoutBG"
                MouseArea {
                    anchors.fill: parent
                    onClicked: appWindow.pageStack.push(aboutPage)
                }
            }

            Text {
                id: txtAppName
                x: 80
                y: 10
                width: timeDiffPage.width - x
                text: qsTr("Time Calculator")
                font.pixelSize: 30
                font.bold: true
                // horizontalAlignment: Text.AlignHCenter
                color: "#3f0064"
                MouseArea {
                    anchors.fill: parent
                    onClicked: appWindow.pageStack.push(aboutPage)
                }
            }
        }


        Flickable {
            id: flick
            anchors.left: parent.left
            anchors.leftMargin: 0
            anchors.top: rowAppLogoName.bottom

            contentHeight: container.width >= 800 ? container.height * 2.2 : container.height * 1

            width: container.width
            height: container.height
            clip: true

            flickableDirection: Flickable.VerticalFlick
            boundsBehavior: Flickable.DragOverBounds

            Row {
                x: 10
                y: 30

                Text {
                    width: timeDiffPage.width - x
                    text: qsTr("Get the time difference between")
                    font.pixelSize: 25
                    font.bold: true
                    color: "#800078"
                }
            }

            Row {
                id: rowDatePicker
                x: 10
                y: 80


                Button{
                    id: btnSelectDate
                    width: 150
                    text: qsTr("Date")
                    opacity: 0.5
                    onClicked: launchDialog1ToToday()
                }

                Text {
                    id: txtSelectedDate
                    color: "#666666"
                    anchors.left: btnSelectDate.right
                    anchors.leftMargin: 20
                    anchors.top: Date.top
                    anchors.topMargin: 10
                    font.pointSize: 18
                }

            }
            Row {
                id: rowTimePicker
                x: 10
                y: 140


                Button{
                    id: btnSelectTime
                    width: 150
                    text: qsTr("Time")
                    opacity: 0.5
                    onClicked: launchDialog1ToTime()
                }

                Text {
                    id: txtSelectedTime
                    color: "#666666"
                    anchors.left: btnSelectTime.right
                    anchors.leftMargin: 20
                    anchors.top: btnSelectTime.top
                    anchors.topMargin: 10
                    font.pointSize: 18
                }


            }

            Row {
                id: rowDateOperation
                x: 10
                y: 200
                width: parent.width

                Text {
                    font.pixelSize: 25
                    font.bold: true
                    color: "#800078"
                    text: qsTr("and")
                }

            }

            Row {
                id: rowDatePicker2
                x: 10
                y: 250


                Button {
                    id: btnSelectDate2
                    width: 150
                    text: qsTr("Date")
                    opacity: 0.5
                    onClicked: launchDialog2ToToday()
                }

                Text {
                    id: txtSelectedDate2
                    color: "#666666"
                    anchors.left: btnSelectDate2.right
                    anchors.leftMargin: 20
                    anchors.top: btnSelectDate2.top
                    anchors.topMargin: 10
                    font.pointSize: 18
                }

            }
            Row {
                id: rowTimePicker2
                x: 10
                y: 310


                Button{
                    id: btnSelectTime2
                    width: 150
                    text: qsTr("Time")
                    opacity: 0.5
                    onClicked: launchDialog2ToTime()
                }

                Text {
                    id: txtSelectedTime2
                    color: "#666666"
                    anchors.left: btnSelectTime2.right
                    anchors.leftMargin: 20
                    anchors.top: btnSelectTime2.top
                    anchors.topMargin: 10
                    font.pointSize: 18
                }
            }

            // Create a selection dialog with a title and list elements to choose from.
            SelectionDialog {
                id: sdUnit
                titleText: qsTr("Unit")
                selectedIndex: 3

                model: unitModel
                onAccepted: {
                    calcResults()
                }
            }


            ListModel {
                id: unitModel	
            }


            Row {
                id: rowResults
                x: 10
                y: 370

                Text {
                    opacity: 0.5
                    width: 30
                    text: qsTr("=")
                    font.pointSize: 18
                    font.bold: true
                }


                Text {
                    id: txtResults
                    font.pointSize: 18
                    font.bold: true
                    color: "#a20407"
                    width: 220
                }

                Button {
                    id: btnSelectUnit
                    width: 150
                    text: sdUnit.model.get(sdUnit.selectedIndex).name
                    opacity: 0.5
                    onClicked: {
                        sdUnit.open()
                    }
                }
            }

            Row {
                x: 10
                y: 430

                Text {
                    id: txtAltResultsEqual
                    opacity: 0.5
                    width: 30
                    text: qsTr("=")
                    font.pointSize: 18
                    font.bold: true
                    visible: false
                }

                Text {
                    id: txtAltResults
                    width: 450
                    text: qsTr( "" )
                    font.pointSize: 18
                    font.bold: false
                    color: "#a20407"
                }
            }

            Row {
                x: 10
                y: 490
                Button {
                    id: btnClear
                    width: 130
                    text: qsTr( "Clear" )
                    opacity: 0.5
                    onClicked: {
                        clear()
                    }
                }
            }

            Image {
                id: imgCalcPlusMinus
                x: timeDiffPage.width - 320; y: 550
                width: 320;
                source: qsTr("qrc:/icon_plusminus")
                MouseArea {
                    anchors.fill: parent
                    onClicked: {
                        appWindow.pageStack.clear()
                        appWindow.pageStack.push(mainPage)
                    }
                }
            }
        }


        DatePickerDialog {
            id: dlgDate
            titleText: qsTr("Select a date")
            minimumYear: 1900
            maximumYear: 2099
            acceptButtonText: qsTr("OK")
            rejectButtonText: qsTr("Cancel")
            onAccepted: selectDateCallbackFunction()
        }

        DatePickerDialog {
            id: dlgDate2
            titleText: qsTr("Select a date")
            minimumYear: 1900
            maximumYear: 2099
            acceptButtonText: qsTr("OK")
            rejectButtonText: qsTr("Cancel")
            onAccepted: selectDate2CallbackFunction()
        }
    }

    function createUnitMenuItems() {
        // console.log("createUnitMenuItems() executed.")
        if (unitModel.count==0) {
            unitModel.append({"name":qsTr("Year(s)")})
            unitModel.append({"name":qsTr("Month(s)")})
            unitModel.append({"name":qsTr("Week(s)")})
            unitModel.append({"name":qsTr("Day(s)")})
            unitModel.append({"name":qsTr("Business Day(s)")})
            unitModel.append({"name":qsTr("Hour(s)")})
            unitModel.append({"name":qsTr("Minute(s)")})
            unitModel.append({"name":qsTr("Second(s)")})
            btnSelectUnit.text = sdUnit.model.get(sdUnit.selectedIndex).name
        }
    }

    function launchDialog1ToToday() {
        if (txtSelectedDate.text=="") {
            var dToday = new Date()
            dlgDate.year = dToday.getFullYear()
            dlgDate.month = dToday.getMonth()+1
            dlgDate.day = dToday.getDate()
        }
        dlgDate.open()
    }

    function launchDialog2ToToday() {
        if (txtSelectedDate2.text=="") {
        var dToday = new Date()
            dlgDate2.year = dToday.getFullYear()
            dlgDate2.month = dToday.getMonth()+1
            dlgDate2.day = dToday.getDate()
        }
        dlgDate2.open()
    }

    function selectDateCallbackFunction() {
        txtSelectedDate.text =  Qt.formatDateTime(new Date(dlgDate.year, dlgDate.month-1, dlgDate.day), "yyyy/MM/dd ddd")
        calcResults()
    }

    function selectDate2CallbackFunction() {
        txtSelectedDate2.text =  Qt.formatDateTime(new Date(dlgDate2.year, dlgDate2.month-1, dlgDate2.day), "yyyy/MM/dd ddd")
        calcResults()
    }


    function calcResults() {
        var dResult = new Date()
        btnSelectUnit.text = sdUnit.model.get(sdUnit.selectedIndex).name

        if (txtSelectedDate.text == "") {
            dlgDate.year = dResult.getFullYear()
            dlgDate.month = dResult.getMonth() + 1
            dlgDate.day = dResult.getDate()
            txtSelectedDate.text = Qt.formatDateTime(dResult, "yyyy/MM/dd ddd")
        }

        if (txtSelectedDate2.text == "") {
            dlgDate2.year = dResult.getFullYear()
            dlgDate2.month = dResult.getMonth() + 1
            dlgDate2.day = dResult.getDate()
            txtSelectedDate2.text = Qt.formatDateTime(dResult, "yyyy/MM/dd ddd")
        }


        var dtDate = new Date(dlgDate.year, dlgDate.month-1, dlgDate.day, dlgTime.hour, dlgTime.minute, dlgTime.second, 0)
        var dtDate2 = new Date(dlgDate2.year, dlgDate2.month-1, dlgDate2.day, dlgTime2.hour, dlgTime2.minute, dlgTime2.second, 0)

        // console.log("dtDate:" + dtDate + " dtDate.getDay: " + dtDate.getDay() + "\ndtDate2: " + dtDate2 + " dtDate2.getDay: " + dtDate2.getDay())

        var fsResult = Math.abs( ( dtDate - dtDate2 ) / 1000 )  // in second

        var fYResult = fsResult / (60*60*24*365.25)
        var fYDecimals = fYResult - Math.floor(fYResult)

        var fMResult = fsResult / (60*60*24*30.4375)
        var fMDecimals = fMResult - Math.floor(fMResult)

        var fWResult = fsResult / (60*60*24*7)
        var fWDecimals = fWResult - Math.floor(fWResult)

        var fDResult = fsResult / (60*60*24)
        var fDDecimals = fDResult - Math.floor(fDResult)

        var fBDResult = dtDate <= dtDate2 ? CalcJSLib.calcBusinessDaysDiff(dtDate,dtDate2) : CalcJSLib.calcBusinessDaysDiff(dtDate2,dtDate)
        var fBDDecimals = fDResult - Math.floor(fDResult)   // use the Day difference decimal part intentionally

        var fHResult = fsResult / (60*60)
        var fHDecimals = fHResult - Math.floor(fHResult)

        var fmResult = fsResult / 60
        var fmDecimals = fmResult - Math.floor(fmResult)

        var fResult = 0

        if (btnSelectUnit.text==qsTr("Year(s)")) {
            fResult = fYResult
            if (fYDecimals > 0) {
                var fYMResult = fYDecimals * 12
                var fYMDecimals = fYMResult - Math.floor(fYMResult)
                var fYMDResult = fYMDecimals * 30.4375
                var fYMDDecimals = fYMDResult - Math.floor(fYMDResult)
                var fYMDHResult = fYMDDecimals * 24
                var fYMDHDecimals = fYMDHResult - Math.floor(fYMDHResult)
                var fYMDHmResult = fYMDHDecimals * 60
                var fYMDHmDecimals = fYMDHmResult - Math.floor(fYMDHmResult)
                var fYMDHmsResult = fYMDHmDecimals * 60
                var fYMDHmsDecimals = fYMDHmsDecimals - Math.floor(fYMDHmsDecimals)

                txtAltResults.text = Math.floor(fYResult) + qsTr(" Yr ") + Math.floor(fYMResult) + qsTr(" Mth ") + Math.floor(fYMDResult) + qsTr(" Day ") + Math.floor(fYMDHResult) + qsTr(" Hr ") + Math.floor(fYMDHmResult) + qsTr(" Min ") + fYMDHmsResult.toFixed(0) + qsTr(" Sec")
                txtAltResultsEqual.visible = true
            }
            else {
                txtAltResults.text = ""
                txtAltResultsEqual.visible = false
            }
        }

        if (btnSelectUnit.text==qsTr("Month(s)")) {
            fResult = fMResult
            if (fMDecimals > 0) {
                var fMDResult = fMDecimals * 30.4375
                var fMDDecimals = fMDResult - Math.floor(fMDResult)
                var fMDHResult = fMDDecimals * 24
                var fMDHDecimals = fMDHResult - Math.floor(fMDHResult)
                var fMDHmResult = fMDHDecimals * 60
                var fMDHmDecimals = fMDHmResult - Math.floor(fMDHmResult)
                var fMDHmsResult = fMDHmDecimals * 60
                var fMDHmsDecimals = fMDHmsDecimals - Math.floor(fMDHmsDecimals)

                txtAltResults.text = Math.floor(fMResult) + qsTr(" Mth ") + Math.floor(fMDResult) + qsTr(" Day ") + Math.floor(fMDHResult) + qsTr(" Hr ") + Math.floor(fMDHmResult) + qsTr(" Min ") + fMDHmsResult.toFixed(0) + qsTr(" Sec")
                txtAltResultsEqual.visible = true
            }
            else {
                txtAltResults.text = ""
                txtAltResultsEqual.visible = false
            }
        }

        if (btnSelectUnit.text==qsTr("Week(s)")) {
            fResult = fWResult
            if (fWDecimals > 0) {
                var fWDResult = fWDecimals * 7
                var fWDDecimals = fWDResult - Math.floor(fWDResult)
                var fWDHResult = fWDDecimals * 24
                var fWDHDecimals = fWDHResult - Math.floor(fWDHResult)
                var fWDHmResult = fWDHDecimals * 60
                var fWDHmDecimals = fWDHmResult - Math.floor(fWDHmResult)
                var fWDHmsResult = fWDHmDecimals * 60
                var fWDHmsDecimals = fWDHmsDecimals - Math.floor(fWDHmsDecimals)

                txtAltResults.text = Math.floor(fWResult) + qsTr(" Wk ") + Math.floor(fWDResult) + qsTr(" Day ") + Math.floor(fWDHResult) + qsTr(" Hr ") + Math.floor(fWDHmResult) + qsTr(" Min ") + fWDHmsResult.toFixed(0) + qsTr(" Sec")
                txtAltResultsEqual.visible = true
            }
            else {
                txtAltResults.text = ""
                txtAltResultsEqual.visible = false
            }
        }

        if (btnSelectUnit.text==qsTr("Day(s)")) {
            fResult = fDResult

            if (fDDecimals > 0) {
                var fDHResult = fDDecimals * 24
                var fDHDecimals = fDHResult - Math.floor(fDHResult)
                var fDHmResult = fDHDecimals * 60
                var fDHmDecimals = fDHmResult - Math.floor(fDHmResult)
                var fDHmsResult = fDHmDecimals * 60
                var fDHmsDecimals = fDHmsDecimals - Math.floor(fDHmsDecimals)

                txtAltResults.text = Math.floor(fDResult) + qsTr(" Day ") + Math.floor(fDHResult) + qsTr(" Hr ") + Math.floor(fDHmResult) + qsTr(" Min ") + fDHmsResult.toFixed(0) + qsTr(" Sec")
                txtAltResultsEqual.visible = true
            }
            else {
                txtAltResults.text = ""
                txtAltResultsEqual.visible = false
            }

        }

        if (btnSelectUnit.text==qsTr("Business Day(s)")) {
            fResult = fBDResult + fDDecimals  // use the Day difference decimal part intentionally

            if (fBDDecimals > 0) {
                var fBDHResult = fBDDecimals * 24
                var fBDHDecimals = fBDHResult - Math.floor(fBDHResult)
                var fBDHmResult = fBDHDecimals * 60
                var fBDHmDecimals = fBDHmResult - Math.floor(fBDHmResult)
                var fBDHmsResult = fBDHmDecimals * 60
                var fBDHmsDecimals = fBDHmsDecimals - Math.floor(fBDHmsDecimals)

                txtAltResults.text = Math.floor(fBDResult) + qsTr(" Day ") + Math.floor(fBDHResult) + qsTr(" Hr ") + Math.floor(fBDHmResult) + qsTr(" Min ") + fBDHmsResult.toFixed(0) + qsTr(" Sec")
                txtAltResultsEqual.visible = true
            }
            else {
                txtAltResults.text = ""
                txtAltResultsEqual.visible = false
            }
        }

        if (btnSelectUnit.text==qsTr("Hour(s)")) {
            fResult = fHResult

            if (fHDecimals > 0) {
                var fHmResult = fHDecimals * 60
                var fHmDecimals = fHmResult - Math.floor(fHmResult)
                var fHmsResult = fHmDecimals * 60
                var fHmsDecimals = fHmsDecimals - Math.floor(fHmsDecimals)

                txtAltResults.text = Math.floor(fHResult) + qsTr(" Hr ") + Math.floor(fHmResult) + qsTr(" Min ") + fHmsResult.toFixed(0) + qsTr(" Sec")
                txtAltResultsEqual.visible = true
            }
            else {
                txtAltResults.text = ""
                txtAltResultsEqual.visible = false
            }
        }


        if (btnSelectUnit.text==qsTr("Minute(s)")) {
            fResult = fmResult

            if (fmDecimals > 0) {
                var fmsResult = fmDecimals * 60
                var fmsDecimals = fmsDecimals - Math.floor(fmsDecimals)

                txtAltResults.text = Math.floor(fmResult) + qsTr(" Min ") + fmsResult.toFixed(0) + qsTr(" Sec")
                txtAltResultsEqual.visible = true
            }
            else {
                txtAltResults.text = ""
                txtAltResultsEqual.visible = false
            }
        }


        if (btnSelectUnit.text==qsTr("Second(s)")) {
            fResult = fsResult
            txtAltResults.text = ""
            txtAltResultsEqual.visible = false
        }

        txtResults.text = fResult.toFixed(4)


    }

    TimePickerDialog {
        id: dlgTime
        titleText: qsTr("Select a time")
        acceptButtonText: qsTr("OK")
        rejectButtonText: qsTr("Cancel")
        onAccepted: selectTimeCallbackFunction()
    }

    TimePickerDialog {
        id: dlgTime2
        titleText: qsTr("Select a time")
        acceptButtonText: qsTr("OK")
        rejectButtonText: qsTr("Cancel")
        onAccepted: selectTime2CallbackFunction()
    }


    function clear() {
        txtSelectedDate.text = ""
        txtSelectedTime.text = ""
        txtSelectedDate2.text = ""
        txtSelectedTime2.text = ""
        dlgTime.hour = 0
        dlgTime.minute = 0
        dlgTime.second = 0
        dlgTime2.hour = 0
        dlgTime2.minute = 0
        dlgTime2.second = 0
        txtResults.text = ""
        txtAltResults.text = ""
        txtAltResultsEqual.visible = false
    }

    function launchDialog1ToTime(hour, minute) {
        if (txtSelectedTime.text=="") {
            var d = new Date()
            dlgTime.hour = d.getHours()
            dlgTime.minute = d.getMinutes()
            dlgTime.second = d.getSeconds()
        }
        dlgTime.hourMode = DateTime.TwentyFourHours
        dlgTime.fields = DateTime.Hours | DateTime.Minutes | DateTime.Seconds;
        dlgTime.open();
    }

    function launchDialog2ToTime(hour, minute) {
        if (txtSelectedTime2.text=="") {
            var d = new Date()
            dlgTime2.hour = d.getHours()
            dlgTime2.minute = d.getMinutes()
            dlgTime2.second = d.getSeconds()
        }
        dlgTime2.hourMode = DateTime.TwentyFourHours
        dlgTime2.fields = DateTime.Hours | DateTime.Minutes | DateTime.Seconds;
        dlgTime2.open();
    }

    function selectTimeCallbackFunction() {
        txtSelectedTime.text =  Qt.formatDateTime(new Date(dlgDate.year, dlgDate.month, dlgDate.day, dlgTime.hour, dlgTime.minute, dlgTime.second), "HH:mm:ss")
        calcResults()
    }

    function selectTime2CallbackFunction() {
        txtSelectedTime2.text =  Qt.formatDateTime(new Date(dlgDate2.year, dlgDate2.month, dlgDate2.day, dlgTime2.hour, dlgTime2.minute, dlgTime2.second), "HH:mm:ss")
        calcResults()
    }

Component.onCompleted: createUnitMenuItems()
}
